<script>
import dayjs from "dayjs";

export default {
  name: "shopDetail",
  data() {
    return {
      detail: {
        name: "",
        description: "",
        isOpen: true,
        openTime: "",
        address: "",
        carouselList: [],
        intro: "",
      },
      dateList: [],
      selectedDateIndex: 0,
      selectedDate: dayjs().format('YYYY-MM-DD'),
      selectedCount: 0,
      totalPrice: "0.00",
      show: false,
      showNoticePopup: false,
      currentNotice: {},
      minDate: dayjs().format('YYYY-MM-DD'),
      maxDate: dayjs().add(9999, 'year').format('YYYY-MM-DD'),
      ticketList: [],
      selectedTicketId: '',
      showBookPopup: false,
      bookForm: {
        name: '',
        phone: '',
        travelDate: dayjs().format('YYYY-MM-DD'),
        peopleCount: 1
      },
      showCalendar: false,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        travelDate: [
          { required: true, message: '请选择出行日期', trigger: 'change' }
        ],
        peopleCount: [
          { required: true, message: '请输入人数', trigger: 'change' }
        ]
      },
      isBooked: false
    };
  },
  watch: {
    selectedDate() {
      this.getTicketList();
    },
    ticketList: {
      handler() {
        this.updateCountAndPrice();
      },
      deep: true
    }
  },
  onLoad({ lineId }) {
    uni.showLoading({
      title: '加载中'
    })
    this.$api.getProductDetail(lineId).then(res => {
      let key = 'sale_count'
      if (res.virtual_sale_count) {
        key = 'virtual_sale_count'
      }
      this.detail = {
        ...res,
        carouselList: res.image_urls ? (res.image_urls || '').split(",") : [res.post_url].filter(i => i),
        saleText: (res[key] > 10000 ? (res[key] / 10000).toFixed(1) + '万+' : res[key] || 0) + '人出游',
      }
    });
    // if (this.$store.state.userInfo.id) {
    //   this.$api.getTicketLineRecordList({
    //     user_id: this.$store.state.userInfo.id,
    //     ticket_line_id: lineId
    //   }).then(res => {
    //     if (res && res.length) {
    //       this.isBooked = true
    //     }
    //   })
    // }
  },
  methods: {
    getSaleCount(item) {
      let key = 'sale_count'
      if (item.virtual_sale_count) {
        key = 'virtual_sale_count'
      }
      return (item[key] > 10000 ? (item[key] / 10000).toFixed(1) + '万+' : item[key] || 0 + '人')
    },
    setDateList(_date = '') {
      let now = _date ? dayjs(_date) : dayjs();
      let dateList = [];
      let _i = 0
      if (!this.detail.isOpen) {
        _i = 1
      }
      for (let i = _i; i < 7; i++) {
        let date = now.add(i, 'day');
        let label = '';
        if (i === 0) label = '今天';
        else if (i === 1) label = '明天';
        else if (i === 2) label = '后天';
        else {
          const weekMap = ['周日','周一','周二','周三','周四','周五','周六'];
          label = weekMap[date.day()];
        }
        dateList.push({
          label,
          date: date.format("YYYY-MM-DD"),
          isToday: i === 0,
        });
      }
      this.dateList = dateList;
      this.selectedDate = this.dateList[this.selectedDateIndex]?.date || '';
    },
    getOpenStatus(openStart, openEnd) {
      let now = new Date().getTime();
      let start = new Date(`${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${openStart}`).getTime();
      let end = new Date(`${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${openEnd}`).getTime();
      return now >= start && now <= end;
    },
    selectDate(idx) {
      this.selectedDateIndex = idx;
      this.selectedDate = this.dateList[idx].date;
    },
    showMoreDate() {
      this.show = true;
    },
    onCalendarConfirm(e) {
      this.bookForm.travelDate = e.result;
      this.showCalendar = false;
    },
    onCalendarClose() {
      this.show = false;
    },
    getTicketList() {
      if (!this.detail.id) return;
      this.$api.getProductList({
        ticket_shop_id: this.detail.id,
      }).then(res => {
        this.ticketList = ( res || []).map(item => {
          return {
            ...item,
            count: 0
          }
        });
      });
    },
    orderTicket() {
      this.showBookPopup = true;
    },
    showNotice(item) {
      this.currentNotice = item;
      this.showNoticePopup = true;
      console.log('00000');

    },
    addCount(item) {
      item.count++;
      this.updateCountAndPrice();
    },
    subCount(item) {
      if (item.count > 0) {
        item.count--;
        this.updateCountAndPrice();
      }
    },
    updateCountAndPrice() {
      let count = 0;
      let price = 0;
      this.ticketList.forEach(item => {
        count += item.count;
        price += item.count * (parseFloat(item.price) || 0);
      });
      this.selectedCount = count;
      this.totalPrice = price.toFixed(2);
    },
    onBookConfirm() {
      if (!this.$store.state.userInfo.id) {
       uni.showModal({
         title: '提示',
         content: '请先登录',
         success: res => {
           if (res.confirm) {
             uni.navigateTo({
               url: '/pages/login/login'
             });
           }
         }
       });
        return;
      }
      if (!this.bookForm.name || !this.bookForm.phone || !this.bookForm.travelDate) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }
      console.log('peopleCount', this.bookForm.peopleCount)
      uni.setStorageSync('selectedTicketList', [
        {
          ...this.detail,
          count: this.bookForm.peopleCount.value || this.bookForm.peopleCount,
          name: this.bookForm.name,
          phone: this.bookForm.phone
        }
      ]);
      uni.navigateTo({
        url: "/pages/cart/payment?type=2&date=" + this.bookForm.travelDate
      })
      return;
      this.$api.createTicketLineRecord({
        ticket_line_id: this.detail.id,
        name: this.bookForm.name,
        phone: this.bookForm.phone,
        travel_date: this.bookForm.travelDate,
        user_id: this.$store.state.userInfo.id || 0,
        people_count: this.bookForm.peopleCount
      }).then(res => {
        uni.showToast({
          title: '预定成功',
          icon: 'success'
        });
        this.showBookPopup = false;
        this.bookForm = {
          name: '',
          phone: '',
          travelDate: dayjs().format('YYYY-MM-DD'),
          peopleCount: 1
        };
      }).catch(err => {
        uni.showToast({
          title: err.message || '预定失败',
          icon: 'none'
        });
      });
    },
    onBookCancel() {
      this.showBookPopup = false;
    },
    onPeopleCountChange(value) {
    }
  }
};
</script>

<template>
  <view class="ticket-detail">
    <!-- 轮播图 -->
    <u-swiper
        :list="detail.carouselList"
        height="500"
        class="carousel"
    >
    </u-swiper>

    <!-- 景点信息 -->
    <view class="main-info">
      <view style="display: flex; justify-content: space-between;">
        <view style="flex-grow: 1" class="title">{{ detail.title }}</view>
        <view class="price">¥{{ detail.price }}起</view>
      </view>
      <view class="desc">{{ detail.description || '' }}</view>
      <view class="address">
        <text>{{ detail.saleText }}</text>
      </view>
    </view>

    <!-- 景点介绍区块 -->
    <view class="section">
      <view class="section-title">线路详情</view>
      <view class="section-content">
        <u-parse :html="detail.content"></u-parse>
      </view>
    </view>
    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <view class="footer-left">
        <u-icon name="share" size="42"></u-icon>
        <view>分享</view>
        <button class="share-btn" open-type="share"></button>
      </view>
      <button
          :class="{disabled: isBooked}" :disabled="isBooked"
          class="footer-btn" @click="orderTicket">
        {{ isBooked ? '已预定' : '立即预定' }}
      </button>
    </view>

    <!-- 预定须知弹窗 -->
    <u-popup v-model="showNoticePopup" mode="bottom" height="70%" border-radius="24">
      <view class="notice-popup">
        <view class="notice-header">
          <text class="notice-title">预定须知</text>
          <u-icon name="close" size="32" @click="showNoticePopup = false"></u-icon>
        </view>
        <scroll-view scroll-y class="notice-content">
          <u-parse :html="currentNotice.content"></u-parse>
        </scroll-view>
      </view>
    </u-popup>

    <!-- 预定弹窗 -->
    <u-popup v-model="showBookPopup" mode="bottom" height="60%" border-radius="24">
      <view class="book-popup">
        <view class="book-header">
          <text class="book-title">预定信息</text>
          <u-icon name="close" size="32" @click="onBookCancel"></u-icon>
        </view>
        <view class="book-form">
          <u-form-item label="姓名" prop="name" :label-width="120">
            <u-input v-model="bookForm.name" placeholder="请输入姓名" />
          </u-form-item>
          <u-form-item label="手机号" prop="phone" :label-width="120">
            <u-input v-model="bookForm.phone" placeholder="请输入手机号" type="number" />
          </u-form-item>
          <u-form-item label="出行日期" prop="travelDate" :label-width="120">
            <view class="date-picker" @click="showCalendar = true">
              <text>{{ bookForm.travelDate }}</text>
              <u-icon name="calendar" size="32" color="#999"></u-icon>
            </view>
          </u-form-item>
          <u-form-item label="数量" prop="peopleCount" :label-width="120">
            <view class="count-picker">
              <u-number-box
                v-model="bookForm.peopleCount"
                :min="1"
                :max="99"
                @change="onPeopleCountChange"
              ></u-number-box>
            </view>
          </u-form-item>
        </view>
        <view class="book-footer">
          <button class="book-btn" @click="onBookConfirm">确认预定</button>
        </view>
      </view>
    </u-popup>

    <!-- 日历弹窗 -->
    <u-calendar
      v-model="showCalendar"
      :min-date="minDate"
      :max-date="maxDate"
      @change="onCalendarConfirm"
      mode="date"
    ></u-calendar>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}
.ticket-detail {
  background: #f5f5f5;
  height: 100%;
  overflow: auto;
  padding-bottom: 50rpx;
}
.main-info {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  margin-top: -40rpx;
  padding: 32rpx;
  overflow: hidden;
  position: relative;
  z-index: 2;
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #222;
  }
  .subtitle {
    color: #6c8cff;
    font-size: 28rpx;
    margin: 8rpx 0;
  }
  .desc {
    color: #999;
    font-size: 26rpx;
    margin-bottom: 8rpx;
  }
  .open-status {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
    .status {
      font-size: 28rpx;
      font-weight: bold;
      margin-right: 16rpx;
      &.open { color: #1ecb8c; }
      &.close { color: #f56c6c; }
    }
    .open-time {
      color: #666;
      font-size: 26rpx;
    }
  }
  .address {
    display: flex;
    align-items: center;
    color: #999;
    font-size: 26rpx;
    .map-btn {
      flex-shrink: 0;
      color: #3a7afe;
      margin-left: 16rpx;
    }
  }
  .price {
    color: #f56c6c;
    font-size: 42rpx;
    font-weight: bold;
    padding-left: 12rpx;
  }
}
.section {
  background: #fff;
  margin-top: 20rpx;
  padding: 24rpx;
  overflow: hidden;
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 12rpx;
  }
  .section-content {
    color: #333;
    font-size: 26rpx;
    line-height: 1.7;
  }
  .date-scroll-wrapper {
    position: relative;
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .more-date {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      border-radius: 16rpx;
      margin-left: 16rpx;
      text-align: center;
      color: #333;
      font-size: 28rpx;
      border: 2rpx solid transparent;
    }
  }
  .date-scroll {
    flex-grow: 1;
    overflow-x: auto;
  }
  .date-row {
    white-space: nowrap;
    display: inline-block;
    min-width: 100%;
  }
  .date-item {
    display: inline-block;
    vertical-align: top;
    background: #f5f5f5;
    border-radius: 16rpx;
    padding: 16rpx 24rpx;
    margin-right: 16rpx;
    text-align: center;
    color: #333;
    font-size: 28rpx;
    border: 2rpx solid transparent;
  }
  .date-item.active {
    background: #fff0e9;
    color: #f56c6c;
    border-color: #f56c6c;
  }
}
.footer-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #fff;
  display: flex;
  justify-content: space-between;

  align-items: center;
  padding: 32rpx 32rpx 72rpx 32rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0,0,0,0.03);
  z-index: 10;
  .footer-left {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 26rpx;
    color: #333;
    position: relative;
    .share-btn {
      position: absolute;
      left:0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
      background: transparent;
      border: none;
      opacity: 0;
    }
    .price {
      color: #f56c6c;
      font-size: 32rpx;
      font-weight: bold;
      margin: 0 8rpx;
    }
    .footer-detail {
      color: #3a7afe;
      margin-left: 12rpx;
      font-size: 24rpx;
    }
  }
  .footer-btn {
    width: 80%;
    background: #4e8ef7;
    color: #fff;
    font-size: 30rpx;
    border-radius: 32rpx;
    padding: 0 48rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-weight: bold;
    margin: 0;
  }
}
.ticket-card {
  background: #fafafa;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  padding: 32rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  &.active {
    border: 2rpx solid #f56c6c;
    background: #fff0e9;
  }
}
.ticket-info {
  flex: 1;
}
.ticket-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 12rpx;
}
.ticket-sale {
  color: #999;
  font-size: 24rpx;
  .notice {
    color: #3a7afe;
    margin-left: 8rpx;
  }
}
.ticket-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.ticket-price {
  color: #f56c6c;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}
.count-btns {
  display: flex;
  align-items: center;
  .plus-btn, .minus-btn {
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    background: #4e8ef7;
    color: #fff;
    font-size: 32rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 8rpx;
  }
  .minus-btn {
    background: #bbb !important;
  }
  .count-group {
    display: flex;
    align-items: center;
  }
  .count-num {
    min-width: 32rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
  }
}
.footer-btn.disabled {
  background: #ccc !important;
  color: #fff !important;
}
.notice-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  .notice-header {
    padding: 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #f5f5f5;
    .notice-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  .notice-content {
    flex: 1;
    padding: 32rpx;
    overflow-y: auto;
  }
}
.book-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  .book-header {
    padding: 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #f5f5f5;
    .book-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  .book-form {
    flex: 1;
    padding: 32rpx;
    overflow-y: auto;
    :deep(.u-form-item) {
      .u-form-item__body {
        .u-form-item__body__left {
          width: 160rpx;
          .u-form-item__body__left__content {
            width: 160rpx;
          }
        }
      }
    }
    .date-picker {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      color: #333;
      font-size: 28rpx;
    }
    .count-picker {
      display: flex;
      align-items: center;
      padding: 10rpx 0;
    }
  }
  .book-footer {
    padding: 32rpx;
    border-top: 2rpx solid #f5f5f5;
    .book-btn {
      width: 100%;
      background: #4e8ef7;
      color: #fff;
      font-size: 30rpx;
      border-radius: 32rpx;
      padding: 0 48rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-weight: bold;
      margin: 0;
    }
  }
}
</style>
